package pubsub;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import org.junit.Test;
import util.ConnUtil;

import java.io.IOException;

/**
 * 发布订阅模式
 * @author TZL
 * @date 2020/8/13
 */
public class Publisher {
    public static final String EXCHANGE_NAME = "publish-subscribe";
    public static final String QUEUE_NAME_1 = "pubsub-queue1";
    public static final String QUEUE_NAME_2 = "pubsub-queue2";

    @Test
    public void publish() throws Exception {
        //1. 获取连接对象
        Connection conn = ConnUtil.getConn();
        //2. 创建通道对象
        Channel channel = conn.createChannel();
        //3.1 创建Exchange
        //String exchange,  交换机的名称
        // BuiltinExchangeType type,指定交换机的类型  FANOUT - pubsub ,   DIRECT - Routing , TOPIC - Topics
        // boolean durable(队列是否持久化), boolean autoDelete（自动删除队列）,
        //        Map<String, Object> arguments
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT,true,false,null);
        //3.2 创建Queue1消息队列
        channel.queueDeclare(QUEUE_NAME_1,true,false,false,null);
        //3.3 创建Queue2
        channel.queueDeclare(QUEUE_NAME_2,true,false,false,null);
        //3.4 queue1绑定到exchange
        channel.queueBind(QUEUE_NAME_1,EXCHANGE_NAME,"");
        //3.5 queue2绑定到exchange
        channel.queueBind(QUEUE_NAME_2,EXCHANGE_NAME,"");
        //4. 发送消息到exchange,指定routingKey
        String msg = "发布订阅的消息!!!!";
        channel.basicPublish(EXCHANGE_NAME,"",null,msg.getBytes());
        //5. close
        channel.close();
        conn.close();



    }

}
